package utils;

import java.io.*;
import java.util.zip.GZIPOutputStream;

public class GzipUtils {
    /**
     * 压缩文件为gzip格式，压缩后删除原文件
     * @param sourceFilePath 原文件路径
     * @return 压缩后文件路径
     */
    public static String compressAndDelete(String sourceFilePath) throws IOException {
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            throw new FileNotFoundException("源文件不存在: " + sourceFilePath);
        }
        String gzipFilePath = sourceFilePath + ".gz";
        try (
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(gzipFilePath);
            GZIPOutputStream gos = new GZIPOutputStream(fos)
        ) {
            byte[] buffer = new byte[8192];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                gos.write(buffer, 0, len);
            }
        }
        // 删除原文件
        if (!sourceFile.delete()) {
            throw new IOException("删除原文件失败: " + sourceFilePath);
        }
        return gzipFilePath;
    }
} 